#include <stdio.h>
#include <unistd.h>

int main(){
    int p1,p2,i;
    int *fp;
    fp = fopen("to_be_locked.txt","w+");
    if(fp==NULL){
        printf("Fail to create File\n");
        exit(-1);
    }
    do{
        p1 = fork();
        if(p1==0){
            lockf(*fp,1,0);
            for(i=0;i<10;i++){
                fprintf(fp,"daughter %d\n",i);
                
            }
            lockf(*fp,0,0);
        }else{
            do{
                p2 = fork();
                if(p2==0){
                    lockf(*fp,1,0);
                    for(int i=0;i<10;i++){
                        fprintf(fp,"son %d\n",i);
                        
                    }
                    lockf(*fp,0,0);
                }else{
                    wait(NULL);
                    lockf(*fp,1,0);
                    for(i = 0;i<10;i++){
                        fprintf(fp,"parent %d\n",i);
                    }
                    lockf(*fp,0,0);
                }
            }while(p2==-1);
        }
    }while(p1==-1);
    fclose(fp);
}